#define _CRT_SECURE_NO_WARNINGS 1

#include "singlelist.h"

SLNode* CreadtNode(SLDateType x)
{
	SLNode* newnode = (SLNode*)calloc(1, sizeof(SLNode));
	if (newnode == NULL)
	{
		perror("CreatNode::calloc");
	}
	newnode->date = x;
	newnode->next = NULL;
	return newnode;
}

void SLPrint(const SLNode* psl)
{
	while (psl)
	{
		printf("%d->", psl->date);
		psl = psl->next;
	}
	printf("NULL\n");
}

void SLPushBack(SLNode** pplist, SLDateType x)
{
	SLNode* newnode = CreadtNode(x);
	if (*pplist == NULL)
	{
		*pplist = newnode;
		return;
	}
	SLNode* end = *pplist;
	while (end->next != NULL)
	{
		end = end->next;
	}
	end->next = newnode;
}

void SLPushFront(SLNode** pplist, SLDateType x)
{
	assert(pplist);
	SLNode* newnode = CreadtNode(x);
	if (*pplist == NULL)
	{
		*pplist = newnode;
		return;
	}
	newnode->next = *pplist;
	*pplist = newnode;
}


void SLPopBack(SLNode** pplist)
{
	assert(pplist);
	if (*pplist == NULL)
	{
		return;
	}
	else if ((*pplist)->next == NULL)
	{
		free(*pplist);
		*pplist = NULL;
		return;
	}
	SLNode* tailprev = *pplist;
	while (tailprev->next->next != NULL)
	{
		tailprev = tailprev->next;
	}
	free(tailprev->next);
	tailprev->next = NULL;
}

void SLPopFront(SLNode** pplist)
{
	assert(pplist);
	if (*pplist == NULL)
	{
		return;
	}
	else if ((*pplist)->next == NULL)
	{
		free(*pplist);
		*pplist = NULL;
		return;
	}
	SLNode* start = (*pplist)->next;
	free(*pplist);
	*pplist = start;
}

SLNode* SLFind(SLNode* psl, SLDateType x)
{
	assert(psl);
	while(psl)
	{
		if (psl->date == x)
		{
			return psl;
		}
		psl = psl->next;
	}
	return NULL;
}

void SLInsertAfter(SLNode* pos, SLDateType x)
{
	assert(pos);
	SLNode* newnode = CreadtNode(x);
	newnode->next = pos->next;
	pos->next = newnode;
}

void SLEraseAfter(SLNode* pos)
{
	assert(pos);
	if (pos->next == NULL)
		return;
	SLNode* delafter = pos->next->next;
	free(pos->next);
	pos->next = delafter;
}


void SLInsert(SLNode** phead, SLNode* pos, SLDateType x)
{
	assert(*phead && phead);
	if (*phead == pos)
	{
		SLPushFront(phead, x);
		return;
	}
	SLNode* cur = *phead;
	while (cur)
	{
		if (cur->next == pos)
		{
			SLInsertAfter(cur, x);
			break;
		}
		cur = cur->next;
	}
}

void SLErase(SLNode** pphead, SLNode* pos)
{
	assert(pphead && *pphead);
	if (*pphead == pos)
	{
		SLNode* tmp = pos->next;
		free(pos);
		*pphead = tmp;
		return;
	}
	SLNode* cur = *pphead;
	while (cur)
	{
		if (cur->next == pos)
		{
			SLNode* tmp = pos->next;
			free(pos);
			cur->next = tmp;
			break;
		}
		cur = cur->next;
	}
}


void SLDestroy(SLNode** pphead)
{
	assert(pphead);
	SLNode* cur;
	while (*pphead)
	{
		cur = (*pphead)->next;
		free(*pphead);
		*pphead = cur;
	}
}

